let app = getApp()
const util = require('../../util/util.js')
Page({
  data: {
    id: 0,
    address: "",
    type: "",
    time: "",
    reporter: "",
    content: "",
    files: [],
    dealContent: "",
    dealFiles: [],
    dealUser: "",
    hide: "",
    loading: 1,
    hasPhone: true,
    buttonused: false,
    dealButton: false,
    modalName: null,
    evalRes: 0, //默认没评价
    couldEval: false, // 是不是自己提交的隐患
    isChargeMan: 0, //判断是否 是当前隐患类型负责人
    buttonTitle: '提醒负责人',
    level: ["/images/star.png",
      "/images/star.png",
      "/images/star.png",
      "/images/star.png",
      "/images/star.png",
    ],
    reporterDingDingId: "",
    video: "",
    videoSrc: "",
    dealVideo: "",
    dealVideoSrc: "",
    isSupervsor: false,
    superviseSchoolId: 0
  },
  /**
  * 生命周期函数--监听页面加载
  */
  onLoad(options) {
    console.log("op", options)
    let that = this
    if (app.globalData.departmentType == "教育局" || app.globalData.departmentType == "区教育局") {
      this.setData({
        isSupervsor: true,
        isSupervising: app.globalData.isSupervising,
        isSuddenSupervising: app.globalData.isSuddenSupervising
      })
    }

    //判断是否 是自己提交的隐患
    if (options.evaluate == 1) {
      this.setData({
        couldEval: true
      })
    }

    if (["-1", "-2"].indexOf(app.globalData.identityId) > -1) {
      this.setData({
        hasPhone: false
      })
    }
    dd.httpRequest({
      url: app.baseUrl + '/DingDingSystem/getSafetySceneById',
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      data: JSON.stringify({
        id: options.id,
      }),
      dataType: 'json',
      success: res => {
        let photo = []
        console.log(res)
        if (res.data.photo == "" || res.data.photo == null) {
          photo.push("/images/nophoto.png")
        } else if (res.data.photo.split(',')) {
          for (let i = 0; i < res.data.photo.split(',').length; i++) {
            photo.push(app.imageUrl + res.data.photo.split(',')[i])
          }
        } else {
          photo.push(app.imageUrl + res.data.photo)
        }

        // 若为已处理，获取已处理信息 
        if (res.data.status == 5) {
          that.setData({
            hide: 'block'
          })
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/getSafetySceneDeal',
            method: 'POST',
            headers: {
              "Content-Type": "application/json"
            },
            data: JSON.stringify({
              id: options.id
            }),
            dataType: 'json',
            success: res => {
              console.log(res)
              let dealphoto = []
              if (res.data.dealPhoto == "" || res.data.dealPhoto == null) {
                dealphoto.push("/images/nophoto.png")
              } else if (res.data.dealPhoto.split(',')) {
                for (let i = 0; i < res.data.dealPhoto.split(',').length; i++) {
                  dealphoto.push(app.imageUrl + res.data.dealPhoto.split(',')[i])
                }
              } else {
                dealphoto.push(app.imageUrl + res.data.dealPhoto)
              }
              that.setData({
                dealPhone: res.data.phone,
                dealContent: res.data.dealContent,
                dealFiles: dealphoto,
                dealVideo: res.data.dealVideo,
                dealVideoSrc: app.imageUrl + res.data.dealVideo,
                dealUser: res.data.strDealUser,
                evalRes: res.data.evaluate ? res.data.evaluate : 0
              })
            },
            fail: res => {
              dd.showToast({
                content: '网络异常！',
                type: 'fail'
              })
            },
            complete: () => {
              that.setData({
                loading: 0
              })
            }
          })
        } else {
          that.setData({
            hide: 'none'
          })
        }
        that.setData({
          status: res.data.status,
          id: res.data.id,
          categoryId: res.data.categoryId,
          address: res.data.address,
          type: res.data.categoryName,
          time: res.data.createTime,
          dealTime: res.data.modifyTime,
          dealContent: res.data.dealContent,
          reporter: res.data.reportName,
          content: res.data.content,
          files: photo,
          video: res.data.video,
          videoSrc: app.imageUrl + res.data.video,
          reportPhone: res.data.phone,
          realname: app.globalData.realname,
          superviseSchoolId: res.data.schoolId
        })
      },
      fail: res => {
        dd.showToast({
          content: '请重试',
          type: 'fail'
        })
      },
      complete: () => {
        // 处理中 直接显示
        if (that.data.status == 7) {
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/getDingDingPushUser',
            method: 'POST',
            headers: {
              "Content-Type": "application/json"
            },
            data: JSON.stringify({
              schoolId: that.data.isSupervsor == true ? that.data.superviseSchoolId : app.globalData.departmentId
            }),
            dataType: 'json',
            success: res => {
              console.log(res)
              that.setData({
                userList: res.data
              })
            }
          })
          that.setData({
            loading: 0
          })
        } else if (that.data.status == 6) {
          // 待处理 判断是否 是隐患负责人
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/getDingDingPushUser',
            method: 'POST',
            headers: {
              "Content-Type": "application/json"
            },
            data: JSON.stringify({
              schoolId: that.data.isSupervsor == true ? that.data.superviseSchoolId : app.globalData.departmentId
            }),
            dataType: 'json',
            success: res => {
              console.log(res)
              that.setData({
                userList: res.data
              })
            }
          })
          that.setData({
            loading: 0
          })
        }
      }
    })
  },
  previewImage(e) {
    if (this.data.files[0] != "/images/nophoto.png") {
      dd.previewImage({
        current: e.currentTarget.id, // 当前显示图片的http链接
        urls: this.data.files // 需要预览的图片http链接列表
      })
    }
  },
  previewImageDeal(e) {
    if (this.data.dealFiles[0] != "/images/nophoto.png") {
      dd.previewImage({
        current: e.currentTarget.id, // 当前显示图片的http链接
        urls: this.data.dealFiles // 需要预览的图片http链接列表
      })
    }
  },
  phoneCall() {
    dd.makePhoneCall({
      phoneNumber: this.data.dealPhone
    })
  },
  phoneCallReport() {
    dd.makePhoneCall({
      phoneNumber: this.data.reportPhone
    })
  },

  remind: function (e) {
    let that = this;
    // let accessToken = dd.getStorageSync({ key: 'accessToken' }) ;
    // console.log("accessToken:"+accessToken)
    dd.confirm({
      title: '提示',
      content: '确定再次提醒处理安全现场？',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      success(result) {
        if (result.confirm) {
          console.log('用户点击确定')
          // 推送
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/getAccessTokenForSendMsg',
            method: 'GET',
            data: {
              schoolId: app.globalData.departmentId
            },
            dataType: 'json',
            success: res => {
              let access_token = res.data.access_token
              dd.httpRequest({
                url: app.baseUrl + '/DingDingSystem/getChargeManDingDingId',
                method: 'POST',
                headers: {
                  "Content-Type": "application/json"
                },
                data: JSON.stringify({
                  categoryId: that.data.categoryId,
                  schoolId: that.data.isSupervsor == true ? that.data.superviseSchoolId : app.globalData.departmentId
                }),
                dataType: 'json',
                success: res => {
                  let unbind = []
                  for (let i = 0; i < res.data.length; i++) {
                    if (res.data[i].res == "success") {
                      let datetime = util.formatTime(new Date())
                      dd.httpRequest({
                        url: app.baseUrl + '/DingDingSystem/sendMessage',
                        headers: {
                          "Content-Type": "application/json"
                        },
                        data: JSON.stringify({
                          schoolId: app.globalData.departmentId,
                          template: 1,
                          accessToken: access_token,
                          touser: res.data[i].msg,
                          safetySceneId: that.data.id,
                          data: {
                            first: {
                              value: "【安全现场隐患】（再次提醒）"
                            },
                            keyword1: {
                              value: app.globalData.realname
                            },
                            keyword2: {
                              value: datetime
                            },
                            keyword3: {
                              value: `有一条${that.data.type}类型隐患长时间未处理，上报人已再次提醒，请及时处理！`
                            }
                          }
                        }),
                        method: 'POST',
                        dataType: 'json',
                        complete: () => {
                          that.setData({
                            buttonused: true,
                            buttonTitle: '已提醒',
                          })
                        }
                      });
                    } else {
                      //获取所有未绑定主管姓名
                      unbind.push(res.data[i].msg)
                    }
                  }
                  //提示未绑定信息
                  if (unbind.length != 0) {
                    let msg = unbind.join("、") + "主管未绑定服务号，无法正常接收推送！"
                    dd.confirm({
                      title: "温馨提示",
                      content: msg,
                    })
                  }
                }
              })
            }
          })
        }
      }
    })
  },

  toDeal: function () {
    let that = this

    // 隐患改变成处理中
    dd.confirm({
      title: '提示',
      content: '确认当前隐患正在被处理中？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')

          //根据上报人姓名获取绑定微信id
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/getDingDingIdByReporterName',
            method: 'GET',
            dataType: 'json',
            data: {
              reporterName: that.data.reporter,
              schoolId: app.globalData.departmentId
            },
            success: res => {
              if (res.data.res == 'success') {
                let reporterDingDingId = res.data.msg
                that.setData({
                  reporterDingDingId: reporterDingDingId,
                  reporterObject: {
                    res: res.data.res,
                    msg: res.data.msg
                  }
                })
              }
            }
          })


          // 推送
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/getAccessTokenForSendMsg',
            method: 'GET',
            data: {
              schoolId: app.globalData.departmentId
            },
            dataType: 'json',
            success: res => {
              let access_token = res.data.access_token
              dd.httpRequest({
                url: app.baseUrl + '/DingDingSystem/getChargeManDingDingId',
                method: 'POST',
                headers: {
                  "Content-Type": "application/json"
                },
                data: JSON.stringify({
                  categoryId: that.data.categoryId,
                  schoolId: app.globalData.departmentId
                }),
                dataType: 'json',
                success: res => {
                  let unbind = []

                  console.log("res.data", res.data)
                  console.log(" res.data.length ", res.data.length)
                  for (let j = 0; j < res.data.length; j++) {
                    if (JSON.stringify(res.data).indexOf(JSON.stringify(that.data.reporterObject)) == -1) {
                      res.data.push(that.data.reporterObject)
                      console.log("进入不相等")
                    } else {
                      console.log("进入相等")
                      break;
                    }
                  }



                  for (let i = 0; i < res.data.length; i++) {
                    if (res.data[i].res == "success") {
                      let datetime = util.formatTime(new Date())
                      dd.httpRequest({
                        url: app.baseUrl + '/DingDingSystem/sendMessage',
                        method: 'POST',
                        headers: {
                          "Content-Type": "application/json"
                        },
                        data: JSON.stringify({
                          schoolId: app.globalData.departmentId,
                          template: 1,
                          accessToken: access_token,
                          touser: res.data[i].msg,
                          safetySceneId: that.data.id,
                          data: {
                            first: {
                              value: `安全隐患由${app.globalData.realname}正在处理`
                            },
                            keyword1: {
                              value: that.data.reporter
                            },
                            keyword2: {
                              value: that.data.time
                            },
                            keyword3: {
                              value: `在${that.data.address}发现${that.data.type}类型隐患，请及时查看！`
                            }
                          }
                        }),
                        dataType: 'json',
                        complete: () => {
                          that.setData({
                            buttonused: true,
                            buttonTitle: '已提醒',
                          })
                        }
                      });
                    } else {
                      //获取所有未绑定主管姓名

                      unbind.push(res.data[i].msg)

                    }
                  }
                  //提示未绑定信息
                  if (unbind.length != 0) {
                    let msg = unbind.join("、") + "主管未绑定服务号，无法正常接收推送！"
                    dd.showToast({
                      content: msg,
                    })
                  }
                }
              })
            }
          })

          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/updateSafetySceneStatus',
            method: 'POST',
            headers: {
              "Content-Type": "application/json"
            },
            data: JSON.stringify({
              safetySceneId: that.data.id,
            }),
            dataType: 'text',
            success: res => {
              console.log(res)
              if (res.data == "success") {
                dd.showToast({
                  content: "变更成功"
                })
                //变成处理中
                that.setData({
                  status: 7
                })

                //变更安全隐患页状态
                let pages = getCurrentPages(); //当前页面
                let prevPage = pages[pages.length - 2]; //上一页面
                prevPage.setData({ //直接给上移页面赋值
                  loadDealing: 1
                });
              } else {
                dd.showToast({
                  content: "变更失败，请重试"
                })
              }

            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  clickLevel: function (e) {
    console.log(e)
    let clickId = parseInt(e.currentTarget.id)
    let tempLevel = []
    let tempLevelFont
    for (let i = 0; i < 5; i++) {
      if (i <= clickId) {
        tempLevel.push("/images/star_fill.png")
      } else {
        tempLevel.push("/images/star.png")
      }
    }
    this.setData({
      level: tempLevel,
      rank: clickId + 1
    })
  },

  evaluate: function () {
    let that = this
    dd.confirm({
      title: '提示',
      content: '是否提交评价',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/updateEvaluate',
            method: 'POST',
            headers: {
              "Content-Type": "application/json"
            },
            dataType: 'text',
            data: JSON.stringify({
              id: that.data.id,
              evaluate: that.data.rank
            }),
            success: res => {
              console.log(res)
              if (res.data == "success") {
                dd.showToast({
                  content: "评价成功"
                })
                that.setData({
                  evalRes: that.data.rank
                })
              } else {
                dd.showToast({
                  content: "评价失败",
                  type: "fail"
                })
              }
            }
          })

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })


  },

  showModal: function () {

    console.log("消息转发=============================")
    this.setData({
      modalName: 'RadioModal'
    })
  },

  hideModal(e) {
    console.log("====")
    this.setData({
      modalName: null
    })
  },

  //新增
  checkboxChange: function (e) {
    console.log(e)
    let userList = []
    let userWechatId = []
    for (var i = 0; i < e.detail.value.length; i++) {
      userWechatId[i] = e.detail.value[i]
    }
    this.setData({
      tempUser: userWechatId
    })
  },

  onConfirm: function (e) {
    console.log("tempuer", this.data.tempUser)
    let that = this
    dd.confirm({
      title: '提示',
      content: `确认将隐患上报处理？`,
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          // 推送
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/getAccessTokenForSendMsg',
            method: 'GET',
            data: {
              schoolId: app.globalData.departmentId
            },
            dataType: 'json',
            success: res => {
              let access_token = res.data.access_token,
                datetime = util.formatTime(new Date())
              for (let i = 0; i < that.data.tempUser.length; i++) {
                dd.httpRequest({
                  url: app.baseUrl + '/DingDingSystem/sendMessage',
                  method: 'POST',
                  headers: {
                    "Content-Type": "application/json"
                  },
                  data: JSON.stringify({
                    schoolId: app.globalData.departmentId,
                    template: 1,
                    accessToken: access_token,
                    touser: that.data.tempUser[i],
                    safetySceneId: that.data.id,
                    data: {
                      first: {
                        value: `安全隐患由${app.globalData.realname}转发给您`
                      },
                      keyword1: {
                        value: that.data.reporter
                      },
                      keyword2: {
                        value: that.data.time
                      },
                      keyword3: {
                        value: `在${that.data.address}发现${that.data.type}类型隐患，请及时查看！`
                      }
                    }
                  }),

                  dataType: 'json',
                  success: res => {
                    dd.showToast({
                      content: "推送成功"
                    })
                    that.setData({
                      dealButton: true,
                      modalName: null
                    })
                  },
                  complete: () => {

                  }
                })
              }
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
});